package com.winchain.chainbill.bill.biz.send.controller;

import com.shell.bee.acct.transaction.vo.AcctInfo;
import com.shell.bee.base.annotation.Logging;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.contract.ContService;
import com.shell.bee.contract.po.ContBas;
import com.shell.bee.entity.mvc.RetMsg;
import com.shell.bee.file.service.PubFileUploadService;
import com.shell.bee.file.vo.FileWapper;
import com.shell.bee.mvc.controller.BaseController;
import com.shell.bee.persistence.model.PageLimit;
import com.shell.constant.rel.AssetCode;
import com.shell.feign.PubDateFeign;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.framework.utils.CommonFileUtil;
import com.shell.framework.utils.ParameterHelper;
import com.shell.governor.modules.vo.ParameterVo;
import com.winchain.chainbill.basic.cus.po.CusGrp;
import com.winchain.chainbill.basic.cus.po.CusRec;
import com.winchain.chainbill.basic.cus.service.CusGrpService;
import com.winchain.chainbill.basic.cus.service.CusRecService;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.po.CbSnd;
import com.winchain.chainbill.bill.biz.query.vo.CbRecQueryVo;
import com.winchain.chainbill.bill.biz.query.vo.CbRecVo;
import com.winchain.chainbill.bill.biz.send.service.BillService;
import com.winchain.chainbill.bill.biz.send.service.BillSndQueryService;
import com.winchain.chainbill.bill.biz.send.service.BillSndRevService;
import com.winchain.chainbill.bill.biz.send.service.BillSndService;
import com.winchain.chainbill.bill.biz.send.vo.BatchBillStats;
import com.winchain.chainbill.bill.biz.send.vo.BillSndVo;
import com.winchain.chainbill.bill.biz.send.vo.ReadEcho;
import com.winchain.chainbill.risk.utill.RateUtil;
import com.winchain.chainbill.trade.service.BillAcctService;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class BillSendController extends BaseController {
	@Autowired
	private BillSndService billSndService;
	@Autowired
	private BillSndQueryService billSndQueryService;
	@Resource(name = "${file.updownload.service}")
	private PubFileUploadService pubFileUploadService;
	@Autowired
	private BillSndRevService billSndRevService;
	@Autowired
	private BillService billService;
	@Autowired
	private BillAcctService billAcctService;
	@Autowired
	private PubDateFeign dateFeign;
	@Autowired
	private CusRecService basCusService;
	@Autowired
	private CusGrpService cusGrpService;
	@Autowired
	private ContService contService;

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "������������������")
	public Map<String, Object> getSendInitData() {
		String buyerId = CommonDataUtil.getCurEntId();
		String billCode = this.billService.getBillCode(buyerId, "R");
		AcctInfo acctInfo = new AcctInfo();
		acctInfo.setCustId(buyerId);
		acctInfo.setAcctType("1");
		acctInfo.setCurrCode(AssetCode.XQT.name());
		List<AcctInfo> results = this.billAcctService.getAcctInfos(acctInfo);
		List<Map<String, Object>> acctInfos = new ArrayList();
		Map<String, Object> acctMap = null;
		CusGrp grp = null;
		ContBas contBas = null;
		CusRec cus = null;
		for (AcctInfo acct : results) {
			if (acct.getBkpCttNo() != null) {
				grp = (CusGrp) this.cusGrpService.selectByKey(acct.getBkpPrdCode());
				contBas = this.contService.getContBas(acct.getBkpId(), "40", "6");
				cus = (CusRec) this.basCusService.selectByKey(contBas.getSponsor());
				acctMap = new HashMap();
				acctMap.put("acctNo", acct.getAcctNo());
				acctMap.put("acctAlias", acct.getBkpCttNo());
				acctMap.put("bkpId", acct.getBkpId());
				acctMap.put("grpId", acct.getBkpPrdCode());
				acctMap.put("finId", contBas.getSponsor());
				acctMap.put("grpCode", grp.getGrpCode());
				acctMap.put("finNm", cus.getCusName());
				acctMap.put("acctAmt", acct.getAcctAmt());
				acctMap.put("acctBlc", acct.getAcctBlc());
				acctMap.put("acctBlk", acct.getAcctBlk());
				acctMap.put("usedAmt", acct.getUsedAmt());
				acctMap.put("availableAmt", acct.getAvailableAmt());
				ParameterVo sndLimtDate = ParameterHelper.getParameter("6", "BILL_SEND_LIM_DATE", acct.getBkpPrdCode());
				String maxLimtDate = "90";
				if ((sndLimtDate != null) && (!StringUtil.empty(sndLimtDate.getParmValue()))) {
					maxLimtDate = sndLimtDate.getParmValue();
				}
				acctMap.put("maxLimtDate", Integer.valueOf(maxLimtDate));
				acctInfos.add(acctMap);
			}
		}
		ParameterVo sndNeedInterest = ParameterHelper.getCommonParameter("SND_NEED_INTEREST");

		Map<String, Object> ret = new HashMap();
		ret.put("billCode", billCode);
		ret.put("acctInfos", acctInfos);
		ret.put("sndNeedInterest", sndNeedInterest.getParmValue());
		ret.put("allHoliday", this.dateFeign.getHoliday("", ""));

		return ret;
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "������������")
	public Map<String, Object> getSndRate(String grpId, String finId) {
		String sndFixedRate = RateUtil.getFixedRate(grpId, finId, "snd_fixed_rate");
		String sndVariableRate = RateUtil.getVariableRate(grpId, finId, CommonDataUtil.getCurEntId(),
				"snd_variable_rate");

		Map<String, Object> ret = new HashMap();
		ret.put("fixedRate", sndFixedRate);
		ret.put("varRate", sndVariableRate);
		return ret;
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "������������")
	public RetMsg sendForMember(CbRec record, CbSnd send, String remark, String attInvoicesJson) {
		send.setBuyerId(CommonDataUtil.getCurEntId());
		send.setBuyerNm(CommonDataUtil.getCurEntName());
		record.setBillType("1");
		this.billSndService.send(record, send, remark, attInvoicesJson, false);
		return new RetMsg("success", false, "��������");
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "����(mobile)", methods = "������������")
	public RetMsg sendForMemberBatch(@RequestBody List<BillSndVo> vos) {
		for (BillSndVo vo : vos) {
			CbRec record = new CbRec();
			CbSnd send = new CbSnd();
			BeanUtils.copyProperties(vo, record);
			BeanUtils.copyProperties(vo, send);
			send.setBuyerId(CommonDataUtil.getCurEntId());
			record.setBillType("1");
			this.billSndService.send(record, send, vo.getRemark(), "", false);
		}
		return new RetMsg("success", false, "��������");
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "����������������")
	public List<CbRecVo> selectBillForSendReview(PageLimit limit, CbRecQueryVo cbRecordQueryVo) {
		return this.billSndQueryService.selectBillForSendReviewByPage(limit, cbRecordQueryVo);
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "��������")
	public CbRecVo selectBillForSend(String billId) {
		return this.billSndQueryService.selectBillForSend(billId);
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "������������")
	public RetMsg reviewPass(String phoneCode, String location, String billIds) throws Exception {
		if (StringUtil.emptyAndNull(billIds)) {
			new RetMsg("error", false, "��������");
		}
		String[] billIdArr = billIds.split(",");
		BatchBillStats<CbSnd> stats = this.billSndRevService.pass(phoneCode, location, billIdArr);
		if (billIdArr.length == stats.getAffectedRows()) {
			return new RetMsg("success", false, "��������������������������������", stats.getTxSnHost());
		}
		if (stats.getAffectedRows() == 0) {
			return new RetMsg("error", false, "������������", CommonFileUtil.changMsg(stats.getAbnormalMsg()));
		}
		return new RetMsg("warning", false, "����������������", CommonFileUtil.changMsg(stats.getAbnormalMsg()));
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "������������")
	public RetMsg reviewReject(String remark, String billIds) throws Exception {
		if (StringUtil.emptyAndNull(billIds)) {
			new RetMsg("error", false, "��������");
		}
		String[] billIdArr = billIds.split(",");
		BatchBillStats<CbSnd> stats = this.billSndRevService.reject(remark, billIdArr);
		if (billIdArr.length == stats.getAffectedRows()) {
			return new RetMsg("success", false, "����������������������������������");
		}
		if (stats.getAffectedRows() == 0) {
			return new RetMsg("error", false, "����������������", CommonFileUtil.changMsg(stats.getAbnormalMsg()));
		}
		return new RetMsg("warning", false, "��������������������", CommonFileUtil.changMsg(stats.getAbnormalMsg()));
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "������������������")
	public ReadEcho read(String fileId, String finId, String finNm) throws Exception {
		ReadEcho echo = this.billSndService.read(this.pubFileUploadService.getDownloadFile(fileId).getFile(), finId,
				finNm);
		if (StringUtil.notTrimEmpty(echo.getError())) {
			String error = CommonFileUtil.changMsg(echo.getError());
			echo.setError(error);
		}
		if (StringUtil.notTrimEmpty(echo.getWarning())) {
			String warning = CommonFileUtil.changMsg(echo.getWarning());
			echo.setWarning(warning);
		}
		return echo;
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "������������")
	public RetMsg impt(String fileId, String grpId, String finId, String finNm, String invoices, String contracts)
			throws Exception {
		this.billSndService.impt(this.pubFileUploadService.getDownloadFile(fileId).getFile(), grpId, finId, finNm,
				invoices, contracts);
		return new RetMsg("success", false, "������������");
	}

	@RequestMapping
	@Logging(module = "��������", methods = "��������")
	public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String pathValue = "/template/excel-import/BuyerBillImport.xlsx";
		String fileName = "����������������.xlsx";
		InputStream is = BillSendController.class.getResourceAsStream(pathValue);
		CommonFileUtil.writeFileToClient(fileName, is, response, request);
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "������������������")
	public List<CbRecVo> getCurrentRejectBills(PageLimit limit) {
		return this.billSndQueryService.selectCurrentRejectBills(limit);
	}

	@RequestMapping
	@ResponseBody
	@Logging(module = "����", methods = "������������������")
	public boolean checkInvoiceNo(String attNo, String billId, String bizId) {
		return this.billSndQueryService.checkInvoiceNo(attNo, billId, bizId);
	}
}
